package br.ufmg.ubicomp.droidguide.communication;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

import br.ufmg.ubicomp.droidguide.common.DroidGuideConfigurationManager;
import br.ufmg.ubicomp.droidguide.common.EntityProperties;
import br.ufmg.ubicomp.droidguide.utils.RequestUtil;

public abstract class CommunicationService {

	//	protected static NodeList processRequest(String url) throws Exception {
	//		/* Make request */
	//		HttpResponse response = processHttpRequest(url);
	//		HttpEntity entity = response.getEntity();
	//		InputStream inStream = entity.getContent();
	//	
	//		/* Parse XML */
	//		DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance()
	//				.newDocumentBuilder();
	//		Document doc = docBuilder.parse(inStream);
	//		// root element.
	//		Element root = doc.getDocumentElement();
	//		// Entities
	//		if (root == null)
	//		{
	//			Log.i("CommunicationService", "root is null!");
	//			return null;
	//		} else 
	//		{
	//			NodeList entities = root.getChildNodes();
	//			return entities;
	//		}
	//	}

	protected static NodeList processRequest(String url) throws Exception {
		/* Make request */
		String httpApi = DroidGuideConfigurationManager.getInstance().getData(
				"httpApi");
		NodeList entities = HttpRequestProcessor.processRequest(httpApi, url);
		return entities;
	}

	//	public static HttpResponse processHttpRequest(String url)
	//			throws IOException, ClientProtocolException {
	//		DefaultHttpClient client = new DefaultHttpClient();
	//		HttpGet method = new HttpGet(url);
	//		Log.d("CommunicationService", url);
	//		HttpResponse response = client.execute(method);
	//		return response;
	//	}

	//	private NotificationManager notificationManager;

	//private final IBinder myBinder = new CommunicationBinder();

	//	public class CommunicationBinder extends Binder {
	//		CommunicationService getService() {
	//			return CommunicationService.this;
	//		}
	//	}

	//	@Override
	//	public void onCreate() {
	//		notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
	//	}

	//	@Override
	//	public IBinder onBind(Intent arg0) {		
	//		return myBinder;
	//	}

	protected String executeUrl(String url) throws IOException {
		String result = RequestUtil.executeUrl(getServerUrl().concat(url));
		return result;
	}

	protected String getServerUrl() {
		String serverUrl = DroidGuideConfigurationManager.getInstance()
				.getData("server");
		return serverUrl;
	}

	public EntityProperties getObject(String key) throws Exception {
		String url = "http://localhost:8080/system/process?operation=get&key="
				+ key;

		NodeList list = processRequest(url);

		return getEntityFromXmlResponse(list);

	}

	private EntityProperties getEntityFromXmlResponse(NodeList list) {
		EntityProperties entity = null;
		for (int i = 0; i < list.getLength(); i++) {
			Node entityEntry = list.item(i);

			if (entityEntry instanceof Element) {
				entity = getEntityElement(entityEntry);
			}
		}
		return entity;
	}

	protected EntityProperties getEntityElement(Node entityEntry) {
		EntityProperties entity = new EntityProperties();
		Element entityElement = (Element) entityEntry;

		entity.setName(entityElement.getTagName());
		entity.setType(entityElement.getAttribute("kind"));

		entity.addProperty("key", entityElement.getAttribute("key"));
		NodeList properties = entityElement.getChildNodes();

		for (int j = 0; j < properties.getLength(); j++) {
			Node propertyEntry = properties.item(j);

			if (propertyEntry instanceof Element) {
				Element propertyElement = (Element) propertyEntry;

				if (propertyElement.getTagName().equals("property")) {
					Text textNode = (Text) propertyElement
							.getFirstChild();
					String text = null;

					if (textNode != null) {
						text = textNode.getData().trim();
					}
					String attributeName = propertyElement
							.getAttribute("name");
					entity.addProperty(attributeName, text);
				}
			}
		}
		return entity;
	}

	public Collection<EntityProperties> getEntitiesFromXmlResponse(NodeList list) {
		Collection<EntityProperties> listEntity = new ArrayList<EntityProperties>();
		
		for (int i = 0; i < list.getLength(); i++) {
			Node entityEntry = list.item(i);
			EntityProperties entity = new EntityProperties();

			if (entityEntry instanceof Element) {
				entity = getEntityElement(entityEntry);
				listEntity.add(entity);
			}
			
		}
		return listEntity;
	}

}
